package com.hengxinguotong.zhihuichengjian.ui.quality;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.DatePicker;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.AccidentAddPersonAdapter;
import com.hengxinguotong.zhihuichengjian.adapter.MeasurePointAdapter;
import com.hengxinguotong.zhihuichengjian.bean.AddGroupPersonnelListRes;
import com.hengxinguotong.zhihuichengjian.bean.Measure;
import com.hengxinguotong.zhihuichengjian.bean.MeasurePoint;
import com.hengxinguotong.zhihuichengjian.bean.MeasurePointRes;
import com.hengxinguotong.zhihuichengjian.bean.Structure;
import com.hengxinguotong.zhihuichengjian.bean.User;
import com.hengxinguotong.zhihuichengjian.ui.AddPersonnelActivity;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.ui.PersonLiableListActivity;
import com.hengxinguotong.zhihuichengjian.ui.SearchNoticedPersonActivity;
import com.hengxinguotong.zhihuichengjian.ui.WebViewActivity;
import com.hengxinguotong.zhihuichengjian.ui.engineering.task.StructureActivity;
import com.hengxinguotong.zhihuichengjian.ui.security.SecurityTestActivity;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXEditTextView;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.view.NotScrollListview;
import com.lidroid.xutils.http.RequestParams;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static cn.jpush.android.api.JPushInterface.a.i;

/**
 * Created by Administrator on 2017/12/18.
 */

public class MeasureActivity extends BaseActivity {
    @BindView(R.id.title_tv)
    HXTextView titleTv;
    @BindView(R.id.back_tv)
    HXTextView backTv;
    @BindView(R.id.submit_tv)
    HXTextView submitTv;
    @BindView(R.id.main_ll)
    LinearLayout mainLl;
    @BindView(R.id.check_date_rl)
    RelativeLayout checkDateRl;
    @BindView(R.id.date_tv)
    HXTextView dateTv;
    @BindView(R.id.structure_tv)
    HXTextView structureTv;
    @BindView(R.id.person_liable_tv)
    HXTextView personLiableTv;
    @BindView(R.id.mobile_rl)
    RelativeLayout mobileRl;
    @BindView(R.id.moblie_tv)
    HXTextView moblieTv;
    @BindView(R.id.company_rl)
    RelativeLayout companyRl;
    @BindView(R.id.company_tv)
    HXTextView companyTv;
    @BindView(R.id.team_rl)
    RelativeLayout teamRl;
    @BindView(R.id.team_tv)
    HXTextView teamTv;
    @BindView(R.id.person_number)
    HXTextView personNumber;
    @BindView(R.id.no_notice_tv)
    HXTextView noNoticeTv;
    @BindView(R.id.add_notice_rv)
    RecyclerView addNoticeRv;
    @BindView(R.id.measure_point_lv)
    NotScrollListview measurePointLv;

    private Measure measure;
    private int type;
    private int year = 0;
    private int monthOfYear = 0;
    private int dayOfMonth = 0;
    private Structure structure;
    private User selectUser;
    private List<User> noticedPersons;//告知人员数组
    private AccidentAddPersonAdapter noticedAdapter;
    private List<MeasurePoint> measurePoints;
    private MeasurePointAdapter measurePointAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_measure);
        ButterKnife.bind(this);
        measure = (Measure) getIntent().getSerializableExtra("measure");
        type = getIntent().getIntExtra("type", 1);
        initView();
    }

    private void initView(){
        if(null == measure){
            switch (type){
                case 1:
                    titleTv.setText("模板实测实量新增");
                    break;
                case 2:
                    titleTv.setText("钢筋实测实量新增");
                    break;
                case 3:
                    titleTv.setText("砼实测实量新增");
                    break;
                case 4:
                    titleTv.setText("砌筑实测实量新增");
                    break;
                case 5:
                    titleTv.setText("抹灰实测实量新增");
                    break;
            }
            Calendar c = Calendar.getInstance();
            year = c.get(Calendar.YEAR);
            monthOfYear = c.get(Calendar.MONTH);
            dayOfMonth = c.get(Calendar.DAY_OF_MONTH);
            dateTv.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
            noticedPersons = new ArrayList<User>();
            noticedPersons.add(getAddUser());
            noticedAdapter = new AccidentAddPersonAdapter(this, noticedPersons, new AccidentAddPersonAdapter.OnRecyclerViewClickListener() {
                @Override
                public void onItemClick(View v, int position) {
                    if (Utils.ADDPIC.equals(noticedPersons.get(position).getHeadPortrait())) {
                        Intent intent = new Intent(MeasureActivity.this, SearchNoticedPersonActivity.class);
                        intent.putExtra("noticedPersons", (Serializable) noticedPersons);
                        startActivityForResult(intent, 2);
                    } else {
                        noticedPersons.remove(position);
                        noticedAdapter.notifyDataSetChanged();
                    }
                }

                @Override
                public void onClick(View v) {

                }
            }, true);
            addNoticeRv.setLayoutManager(getLinearLayoutManager());
            addNoticeRv.setAdapter(noticedAdapter);
            personNumber.setText("已选择" + (noticedPersons.size()-1) + "人");
            getMesasurePointsList(type);
        }else{
            switch (type){
                case 1:
                    titleTv.setText("模板实测实量详情");
                    break;
                case 2:
                    titleTv.setText("钢筋实测实量详情");
                    break;
                case 3:
                    titleTv.setText("砼实测实量详情");
                    break;
                case 4:
                    titleTv.setText("砌筑实测实量详情");
                    break;
                case 5:
                    titleTv.setText("抹灰实测实量详情");
                    break;
            }
            submitTv.setVisibility(View.GONE);
            Utils.setEditTextViewUnable(measure.getInspectDate(), dateTv);//检查日期
            Utils.setEditTextViewUnable(measure.getProjectStructureName(), structureTv);//检查部位
            Utils.setEditTextViewUnable(measure.getContactName(), personLiableTv);//责任人
            if(null != measure.getProjectCompanyName()){
                companyRl.setVisibility(View.VISIBLE);
                Utils.setEditTextViewUnable(measure.getProjectCompanyName(), companyTv);//所属公司
            }
            if(null != measure.getTeamName()){
                teamRl.setVisibility(View.VISIBLE);
                Utils.setEditTextViewUnable(measure.getTeamName(), teamTv);//所属班组
            }
            if(null != measure.getContactMobile()){
                mobileRl.setVisibility(View.VISIBLE);
                Utils.setEditTextViewUnable(measure.getContactMobile(), moblieTv);//责任人电话
            }
            getUserList(measure.getId());//获取告知人列表
            getMeasureResultsList(measure.getId());//得到检查要点结果信息
        }
    }

    @OnClick({R.id.back_tv, R.id.submit_tv, R.id.check_date_rl, R.id.structure_tv, R.id.person_liable_tv})
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.back_tv:
                finish();
                break;
            case R.id.submit_tv:
                addMeasure();
                break;
            case R.id.check_date_rl:
                showWheelViewDialog();
                break;
            case R.id.structure_tv:
                intent = new Intent(MeasureActivity.this, StructureActivity.class);
                StructureActivity.FROM = 7;
                startActivity(intent);
                break;
            case R.id.person_liable_tv:
                intent = new Intent(MeasureActivity.this, PersonLiableListActivity.class);
                intent.putExtra("type", 0);
                startActivityForResult(intent, 1);
                break;
        }
    }

    private boolean checkContent() {
//        if (structure == null) {
//            showToast("请选择工程结构");
//            return false;
//        }

        for(int i=0; i<measurePointLv.getChildCount(); i++){
            LinearLayout layout = (LinearLayout) measurePointLv.getChildAt(i);
            HXEditTextView totalQtyEt = (HXEditTextView) layout.findViewById(R.id.checked_count_etv);
            String totalQty = totalQtyEt.getText().toString();
            HXEditTextView passQtyEt = (HXEditTextView) layout.findViewById(R.id.passed_count_etv);
            String passQty = passQtyEt.getText().toString();
            if(totalQty == null || Utils.isEmpty(totalQty) || passQty == null || Utils.isEmpty(passQty)){
                showToast("请填写完毕所有检查要点信息");
                return false;
            }else{
                MeasurePoint measurePoint = measurePoints.get(i);
                measurePoint.setPassQty(passQty);
                measurePoint.setTotalQty(totalQty);
            }
        }

        if(selectUser == null){
            showToast("请选择责任人");
            return false;
        }

        return true;

    }

    private void addMeasure() {
        if (!checkContent()) {
            return;
        }
        RequestParams params = new RequestParams();
        params.addBodyParameter("constructionId", SPUtil.getString(this, "constructionid"));
        params.addBodyParameter("type", type + "");
        params.addBodyParameter("inspectDate", year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
        if(null != structure)
            params.addBodyParameter("projectStructureId", structure.getId());

        params.addBodyParameter("contactId", selectUser.getUserId());
        if(selectUser.getMobile() != null){
            params.addBodyParameter("contactMobile", selectUser.getMobile());
        }
        if(selectUser.getProjectCompanyId() != null){
            params.addBodyParameter("projectCompanyId", selectUser.getProjectCompanyId());
        }
        if(selectUser.getTeamId() != null){
            params.addBodyParameter("teamId", selectUser.getTeamId());
        }
//        params.addBodyParameter("remark", remarkEtv.getEditableText().toString());

        if(noticedPersons != null && noticedPersons.size()>0){
            JSONArray userArray = new JSONArray();
            try {
                for(int i=1;i<noticedPersons.size();i++) {
                    JSONObject object = new JSONObject();
                    object.put("userId",noticedPersons.get(i).getUserId());
                    object.put("projectCompanyId",noticedPersons.get(i).getProjectCompanyId());
                    object.put("teamId",noticedPersons.get(i).getTeamId());
                    object.put("mobile",noticedPersons.get(i).getMobile());
                    userArray.put(object);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            params.addBodyParameter("userList", userArray.toString());
        }

        JSONArray measurePointArray = new JSONArray();
        try {
            for(int i=0; i<measurePoints.size(); i++){
                JSONObject object = new JSONObject();
                object.put("measurePointId", measurePoints.get(i).getId());
                object.put("totalQty", measurePoints.get(i).getTotalQty());
                object.put("passQty", measurePoints.get(i).getPassQty());
                measurePointArray.put(object);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.addBodyParameter("measureResultsList", measurePointArray.toString());

        Utils.requestData(getResources().getString(R.string.loading), this, "/inspection/measure/save/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    int status = object.getInt("status");
                    String msg = object.getString("msg");
                    if(status == 1){
                        showToast("提交成功");
                        setResult(1);
                        finish();
                    }else{
                        showToast(msg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String json) {
                try {
                    JSONObject object = new JSONObject(json);
                    String msg = object.getString("msg");
                    showToast(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent.getSerializableExtra("struct") != null) {
            structure = (Structure) intent.getSerializableExtra("struct");
            structureTv.setText(structure.getName());
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(data != null) {
            switch (requestCode) {
                case 1:
                    selectUser = new User();
                    selectUser = (User) data.getSerializableExtra("selectUser");
                    processUser(selectUser);
                    break;
                case 2:
                    List<User> temp = (List<User>) data.getSerializableExtra("selectNoticers");
                    for (int i = 0; i < temp.size(); i++) {
                        User user = temp.get(i);
                        if (!user.isInUsers(noticedPersons)) {
                            noticedPersons.add(user);
                        }
                    }
                    noticedAdapter.notifyDataSetChanged();
                    personNumber.setText("已选择" + (noticedPersons.size()-1) + "人");
                    break;
            }
        }
    }

    private void processUser(User user){
        personLiableTv.setText(user.getName());
        if(user.getMobile() != null){
            mobileRl.setVisibility(View.VISIBLE);
            moblieTv.setText(user.getMobile());
        }
        if(user.getProjectCompanyId() != null && user.getProjectCompanyName() != null){
            companyRl.setVisibility(View.VISIBLE);
            companyTv.setText(user.getProjectCompanyName());
        }
        if(user.getTeamId() != null && user.getTeamName() != null){
            teamRl.setVisibility(View.VISIBLE);
            teamTv.setText(user.getTeamName());
        }
    }

    private void showWheelViewDialog() {
        new DatePickerDialog(this,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        MeasureActivity.this.year = year;
                        MeasureActivity.this.monthOfYear = monthOfYear;
                        MeasureActivity.this.dayOfMonth = dayOfMonth;
                        dateTv.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
                    }
                },
                year, monthOfYear, dayOfMonth).show();
    }

    private User getAddUser() {
        User addUser = new User();
        addUser.setHeadPortrait(Utils.ADDPIC);
        addUser.setUserId("-1");
        addUser.setName("");
        return addUser;
    }

    private LinearLayoutManager getLinearLayoutManager() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        return linearLayoutManager;
    }

    private void getMeasureResultsList(String measureId){
        Utils.requestData(null, this, "/inspection/measure/queryMeasureResultsList/" + SPUtil.getString(this, "uuid") + "?id=" + measureId, null, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    MeasurePointRes measurePointRes = gson.fromJson(json, MeasurePointRes.class);
                    if(measurePointRes.getStatus() == 1){
                        measurePointAdapter = new MeasurePointAdapter(measurePointRes.getValue(), MeasureActivity.this, 0, mainLl);//0查看详情 1输入数据；
                        measurePointLv.setAdapter(measurePointAdapter);
                    }else{
                        showToast(measurePointRes.getMsg());
                    }
                }
            }

            @Override
            public void onFailure(String json) {

            }
        });
    }

    private void getMesasurePointsList(int type){
        Utils.requestData(null, this, "/inspection/measure/queryMeasurePointList/" + SPUtil.getString(this, "uuid") + "?type=" + type, null, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    MeasurePointRes measurePointRes = gson.fromJson(json, MeasurePointRes.class);
                    if(measurePointRes.getStatus() == 1){
                        measurePoints = measurePointRes.getValue();
                        measurePointAdapter = new MeasurePointAdapter(measurePoints, MeasureActivity.this, 1, mainLl);//0查看详情 1输入数据；
                        measurePointLv.setAdapter(measurePointAdapter);
                    }else{
                        showToast(measurePointRes.getMsg());
                    }
                }
            }

            @Override
            public void onFailure(String json) {

            }
        });
    }

    private void getUserList(String measureId) {

        Utils.requestData(null, this, "/inspection/queryNotifyByInspectionId/" + SPUtil.getString(this, "uuid") + "?id=" + measureId, null, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    AddGroupPersonnelListRes personnelListRes = gson.fromJson(json, AddGroupPersonnelListRes.class);
                    if(personnelListRes.getStatus() == 1){
                        processNoticers(personnelListRes.getValue());
                    }else{
                        showToast(personnelListRes.getMsg());
                    }
                }
            }

            @Override
            public void onFailure(String json) {

            }
        });
    }

    private void processNoticers(final List<User> noticers){
        if (noticers.size() == 0) {
            noNoticeTv.setVisibility(View.VISIBLE);
        } else {
            noticedAdapter = new AccidentAddPersonAdapter(this, noticers, new AccidentAddPersonAdapter.OnRecyclerViewClickListener() {
                @Override
                public void onItemClick(View v, int position) {
//                    Intent intent = new Intent(MeasureActivity.this, AddPersonnelActivity.class);
//                    intent.putExtra("type", AddPersonnelActivity.MODTYPE);
//                    intent.putExtra("personId", noticers.get(position).getPersonId());
//                    startActivity(intent);
                }

                @Override
                public void onClick(View v) {

                }
            }, false);
            addNoticeRv.setLayoutManager(getLinearLayoutManager());
            addNoticeRv.setAdapter(noticedAdapter);
            personNumber.setText("已选择" + noticers.size() + "人");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        ButterKnife.unbind(this);
    }

}
